﻿using System;
using System.Data.SqlServerCe;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace PWDepositary
{
    public partial class Form3 : Form
    {
        CustomBorder _tBxPwBorder;
        private SqlCeConnection connection;
        public Form3()
        {
            InitializeComponent();
            _tBxPwBorder = new CustomBorder(tBxPW) {BorderColor = Color.SteelBlue, RoundSize = new Size(7, 7)};
            // ускоряем подключение к бд
            var load = new Thread(LoadSQL);
            load.Start();
        }

        private void menuItemOK_Click(object sender, EventArgs e)
        {
            if (tBxPW.Text == string.Empty)
            {
                _tBxPwBorder.BorderColor = Color.Red;
                return;
            }
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                connection = new SqlCeConnection(Database.ConnectString + tBxPW.Text);
                connection.Open();
                Database.ConnectStringFull = Database.ConnectString + tBxPW.Text;
                Close();
            }
            catch
            {
                if (MessageBox.Show("Вероятно пароль набран не верно, попробовать еще раз?", "Ошибка",
                                MessageBoxButtons.RetryCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Retry)
                {
                    tBxPW.Text = "";
                    _tBxPwBorder.BorderColor = Color.Red;
                }
                else
                {
                    Application.Exit();
                }
            }
            finally
            {
                Cursor.Current = Cursors.Default;
                if (connection != null) connection.Close();
            }
        }

        private void menuItemCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Form3_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                menuItemOK_Click(sender, e);
            }
        }

        private void tBxPW_KeyUp(object sender, KeyEventArgs e)
        {
            Form3_KeyUp(sender, e);
        }

        private void LoadSQL()
        {
            Thread.CurrentThread.Join(100);
            try
            {
                connection = new SqlCeConnection(Database.ConnectString);
                connection.Open();
            }
            catch
            {
            }
            finally 
            {
                connection.Close();
            }

        }
    }
}